package com.lance.answer.question_answer;

import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;
import com.lance.answer.gui.answer.AnswerObject;
import com.lance.answer.gui.answer.Util;
import com.lance.answer.gui.answer.gk.DealInfoUtil;
import com.lance.answer.util.Constant;
import com.lance.answer.util.MD5Utils;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.interactions.Actions;
import org.springframework.util.CollectionUtils;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Slf4j
public class QuestionAnswerbinglixue {

    /**
     * 进度表：
     * 6-18 19:55开始测试 公共行政学 行政管理专科
     *
     * @param args
     * @throws Exception
     */
    public static void main(String[] args) throws Exception {


        //学科中文名
        String subjectName = "病理学与病理生理学";
        //专业中文名
       // String majorName = "药学专科2103";
        //并发开启的浏览器数量
        int sync = 6;
        //是否提交答案
        boolean commit = true;
        //驱动路径
        String driverPath = null;

        //初始化日志配置
        Constant.initLog();
        //开启任务
        System.out.println("刷题课程：     " + subjectName);
      //  System.out.println("刷题专业：     " + majorName);
        System.out.println("并发开启浏览器：" + sync);
        System.out.println("是否提交答案：  " + commit);
        start(subjectName, sync, driverPath, commit);
    }

    public static void start(String subjectName,  int sync, String driverPath, boolean commit) throws Exception {
        //获取模板路径,通过流的方式获取文件可以避免被打成jar包之后无法获取文件路径的异常
        InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(subjectName + "/" + subjectName + "-answer.json");
        String answerStr = IOUtils.toString(inputStream);

        List<AnswerObject> list = JSONObject.parseArray(answerStr, AnswerObject.class);
        Map<String, AnswerObject> map = new HashMap<>();
        for (AnswerObject answerObject : list) {
            map.put(answerObject.getQuestionCode(), answerObject);
        }

//        InputStream inputStream2 = Thread.currentThread().getContextClassLoader().getResourceAsStream(subjectName + "/" + "users/" + majorName + ".user");
//        List<String> users = IOUtils.readLines(inputStream2, "utf-8");

        InputStream inputStream3 = Thread.currentThread().getContextClassLoader().getResourceAsStream(subjectName + "/" + subjectName + "-quiz.section");
        List<String> list1 = IOUtils.readLines(inputStream3);
        List<String> paths = new ArrayList<>();
        for (String str : list1) {
            paths.add(str.split(",")[0].trim());
        }

        String teacher = "刘";
        List<String> userNames = DealInfoUtil.countUserCourseInfo("libs//userCourseInfo//"+teacher).get(subjectName);

        InputStream inputStream2 = new FileInputStream("libs//teachers//"+teacher+".user");
        List<String> userString2 = IOUtils.readLines(inputStream2, "utf-8");

        Map<String, String> usernameAndPwd = Maps.newHashMap();
        for (String user : userString2) {
            String[] strs = user.split(",");
            String userCode = strs[0];
            String pwd = strs[1].substring(6, 14);
            pwd = "Ouchn" + pwd;
            usernameAndPwd.put(userCode, pwd);
        }

        List<List<String>> group = new ArrayList<>();
        int size = userNames.size();
        int step = size / sync;
        if (step == 0) {
            group.add(userNames);
        } else {
            for (int i = 0; i < sync; i++) {
                List<String> list2 = userNames.subList(step * i, (i + 1) * step);
                group.add(list2);
            }
            group.add(userNames.subList(step * sync, userNames.size()));
        }
        for (List<String> batchUser : group) {
            Constant.THREAD_POOL_BATCH.execute(() -> {
                try {
                    for (String user : batchUser) {
                        String userCode = user;
                        String pwd = usernameAndPwd.get(userCode);
                        //      String pwd = strs[1];
                        run(paths, map, subjectName, driverPath, userCode, pwd, commit);
                    }

                } catch (IOException e) {
                    e.printStackTrace();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            });

        }





    }


    // 管理学基础 2065001457555 19940419
    public static void run(List<String> urlTasks, Map<String, AnswerObject> answers, String subjectName, String driverPath, String userName, String password, boolean commit) throws Exception {
        WebDriver driver = Util.getDriver(driverPath);
        //String url = "http://student.ouchn.cn/";
        String url = "http://passport.ouchn.cn/Account/Login?ReturnUrl=%2Fconnect%2Fauthorize%2Fcallback%3Fclient_id%3Dstudentspace%26redirect_uri%3Dhttp%253A%252F%252Fstudent.ouchn.cn%252F%2523%252Fsignin-oidc%2523%26response_type%3Did_token%2520token%26scope%3Dopenid%2520profile%2520ouchnuser%2520ouchnstudentspaceapi%2520offline_access%26state%3Dca1cb5d0270b49fdaea508b8a846c457%26nonce%3Dd257df51b0a141ac8ed35b1caf59ef4c";
        driver.get(url);
        Thread.sleep(3000);
        //Util.login(driver, "2065001457555", "19940419");
        Util.login(driver, userName, password);
        Util.switchToFirst(driver);
        Thread.sleep(3000);
        // 形考作业的链接 管理学
        //List<String> urlTasks = Util.getCourseTaskUrl(driver, CourseTypeEnum.BasicManagement.name);
        //List<String> urlTasks = Util.getCourseTaskUrl(subjectCode);

        //chromeDriver.navigate().refresh();
        for (WebElement we : driver.findElements(By.className("media-body"))) {
            Util.switchToFirst(driver);
            // 找到管理学基础
            String mediaTitle = we.findElement(By.className("media-title")).getText();

            if (!mediaTitle.contains(subjectName)) {
                continue;
            }
            //点击进入学习的按钮
            WebElement studyButton = we.findElement(By.cssSelector("button[class='btn bg-primary']"));
            studyButton.click();
            //Util.switchToLast(driver);
            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        System.out.println(urlTasks.toString());
        for (String urlTask : urlTasks) {
           try {
               // FIXME 当完成第一份形考任务时，必须提交，否则会弹出 ”是否保存当前页面“消息
               driver.get(urlTask);
               Thread.sleep(2 * 1000);
               // 点击继续作业

               boolean isGoOn = true;
               for (WebElement we : driver.findElements(By.cssSelector("*[class='btn btn-secondary']"))) {
                   if ("重新试答测验".equals(we.getText())) {
                       isGoOn = false;
                   }
               }
               for (WebElement we : driver.findElements(By.tagName("a"))) {
                   if ("回顾".equals(we.getText())) {
                       isGoOn = false;
                   }
               }
               if (!isGoOn) {
                   continue;
               }

               try {
                   WebElement doWorkArea = driver.findElement(By.cssSelector("div[class='box py-3 quizattempt']"));
                   doWorkArea.findElement(By.cssSelector("button[class='btn btn-secondary']")).click();
               } catch (Exception e) {
                   System.err.println("taskUrl:" + urlTask + "  occur error");
                   e.printStackTrace();
               }
               Thread.sleep(2 * 1000);
               //回到试题首页
               WebElement element = driver.findElement(By.id("quiznavbutton1"));
               element.click();
               Thread.sleep(2 * 1000);
               // 回到首页
               //Util.goHomePageIndex(driver);

               Map<String, String> DragPictureMap = Maps.newHashMap();


               boolean hashNextPage = true;
               while (hashNextPage) {
                   try {
                       Thread.sleep(4000);
                       // 单个页面的所有题目的集合
                       List<WebElement> singlePageQuestion = Util.getSinglePageQuestionList(driver);
                       // 遍历每个问题|题目


                       for (WebElement singleSubject : singlePageQuestion) {

                           WebElement contentElement = singleSubject.findElement(By.className("content"));

                           //                      String title ;
//                        String answerClass = singleSubject.getAttribute("class");
//                        if (answerClass.contains("multianswer")) {
//                            title = Util.getTitle(contentElement);
//                        }else {
////                            // qtext 题目标题
////                            WebElement qTitleElement = contentElement.findElement(By.className("qtext"));
////                            // 题目名称
////                             title = qTitleElement.getText();
//
//                        }
                           String title = Util.getTitle(contentElement);
                           //兼容特殊字符
                           title = Util.dealContent(title);

                           String questionCode = MD5Utils.encode(subjectName + title);


                           if (!answers.containsKey(questionCode)) {

                               Map<String, String> dragPictureMap = Maps.newHashMap();

                               // 形考一--------------------------------
                               dragPictureMap.put("肺出血性梗死","http://xinjiang.ouchn.cn/pluginfile.php/465002/qtype_ddmatch/subanswer/4958426/26/854/%E8%82%BA%E5%87%BA%E8%A1%80%E6%80%A7%E6%A2%97%E6%AD%BB.jpg");

                               dragPictureMap.put("肝细胞脂肪变性","http://xinjiang.ouchn.cn/pluginfile.php/465002/qtype_ddmatch/subanswer/4958426/26/855/%E8%82%9D%E7%BB%86%E8%83%9E%E8%84%82%E8%82%AA%E5%8F%98%E6%80%A7.jpg");
                               dragPictureMap.put("肾压迫性萎缩","http://xinjiang.ouchn.cn/pluginfile.php/465002/qtype_ddmatch/subanswer/4958426/26/857/%E8%82%BE%E5%8E%8B%E8%BF%AB%E6%80%A7%E8%90%8E%E7%BC%A9.jpg");
                               dragPictureMap.put("心肌凝固性坏死","http://xinjiang.ouchn.cn/pluginfile.php/465002/qtype_ddmatch/subanswer/4958426/26/858/%E5%BF%83%E8%82%8C%E5%87%9D%E5%9B%BA%E6%80%A7%E5%9D%8F%E6%AD%BB.jpg");

                               dragPictureMap.put("槟榔肝","http://xinjiang.ouchn.cn/pluginfile.php/465002/qtype_ddmatch/subanswer/4958426/26/853/%E6%A7%9F%E6%A6%94%E8%82%9D.jpg");
                               dragPictureMap.put("肾贫血性坏死","http://xinjiang.ouchn.cn/pluginfile.php/465002/qtype_ddmatch/subanswer/4958426/26/856/%E8%82%BE%E8%B4%AB%E8%A1%80%E6%80%A7%E5%9D%8F%E6%AD%BB.jpg");
                               dragPictureMap.put("血管内混合血栓","http://xinjiang.ouchn.cn/pluginfile.php/465002/qtype_ddmatch/subanswer/4958426/26/859/%E8%A1%80%E7%AE%A1%E5%86%85%E6%B7%B7%E5%90%88%E8%A1%80%E6%A0%93.jpg");
                               dragPictureMap.put("足干性坏疽","http://xinjiang.ouchn.cn/pluginfile.php/465002/qtype_ddmatch/subanswer/4958426/26/860/%E8%B6%B3%E5%B9%B2%E6%80%A7%E5%9D%8F%E7%96%BD.jpg");
                               // 形考一--------------------------------

                               // 形考二--------------------------------
                               dragPictureMap.put("肺内的转移癌（肉眼观）","http://xinjiang.ouchn.cn/pluginfile.php/465002/qtype_ddmatch/subanswer/4959671/26/861/%E8%82%BA%E5%86%85%E7%9A%84%E8%BD%AC%E7%A7%BB%E7%99%8C%EF%BC%88%E8%82%89%E7%9C%BC%E8%A7%82%EF%BC%89.JPG");
                               dragPictureMap.put("乳腺癌（蔓延到皮肤，肉眼观）","http://xinjiang.ouchn.cn/pluginfile.php/465002/qtype_ddmatch/subanswer/4959671/26/862/%E4%B9%B3%E8%85%BA%E7%99%8C%EF%BC%88%E8%94%93%E5%BB%B6%E5%88%B0%E7%9A%AE%E8%82%A4%EF%BC%8C%E8%82%89%E7%9C%BC%E8%A7%82%EF%BC%89.jpg");
                               // 形考二--------------------------------


                               // 形考三--------------------------------
                               dragPictureMap.put("肺癌（中央型，肉眼观）-换图","http://xinjiang.ouchn.cn/pluginfile.php/465002/qtype_ddmatch/subanswer/4959982/26/863/%E8%82%BA%E7%99%8C%EF%BC%88%E4%B8%AD%E5%A4%AE%E5%9E%8B%EF%BC%8C%E8%82%89%E7%9C%BC%E8%A7%82%EF%BC%89-%E6%8D%A2%E5%9B%BE.jpg");
                               dragPictureMap.put("肺气肿（镜下观）","http://xinjiang.ouchn.cn/pluginfile.php/465002/qtype_ddmatch/subanswer/4959982/26/864/%E8%82%BA%E6%B0%94%E8%82%BF%EF%BC%88%E9%95%9C%E4%B8%8B%E8%A7%82%EF%BC%89.jpg");
                               dragPictureMap.put("高血压病脑出血（内囊出血，肉眼观）","http://xinjiang.ouchn.cn/pluginfile.php/465002/qtype_ddmatch/subanswer/4959982/26/865/%E9%AB%98%E8%A1%80%E5%8E%8B%E7%97%85%E8%84%91%E5%87%BA%E8%A1%80%EF%BC%88%E5%86%85%E5%9B%8A%E5%87%BA%E8%A1%80%EF%BC%8C%E8%82%89%E7%9C%BC%E8%A7%82%EF%BC%89.jpg");
                               dragPictureMap.put("冠状动脉硬化（3级，镜下观）","http://xinjiang.ouchn.cn/pluginfile.php/465002/qtype_ddmatch/subanswer/4959982/26/866/%E5%86%A0%E7%8A%B6%E5%8A%A8%E8%84%89%E7%A1%AC%E5%8C%96%EF%BC%883%E7%BA%A7%EF%BC%8C%E9%95%9C%E4%B8%8B%E8%A7%82%EF%BC%89.jpg");
                               dragPictureMap.put("溃疡病","http://xinjiang.ouchn.cn/pluginfile.php/465002/qtype_ddmatch/subanswer/4959982/26/867/%E6%BA%83%E7%96%A1%E7%97%85.jpg");
                               dragPictureMap.put("食道癌（髓质型）","http://xinjiang.ouchn.cn/pluginfile.php/465002/qtype_ddmatch/subanswer/4959982/26/868/%E9%A3%9F%E9%81%93%E7%99%8C%EF%BC%88%E9%AB%93%E8%B4%A8%E5%9E%8B%EF%BC%89.jpg");
                               dragPictureMap.put("粥样斑块（肉眼观）","http://xinjiang.ouchn.cn/pluginfile.php/465002/qtype_ddmatch/subanswer/4959982/26/869/%E7%B2%A5%E6%A0%B7%E6%96%91%E5%9D%97%EF%BC%88%E8%82%89%E7%9C%BC%E8%A7%82%EF%BC%89.jpg");
                               // 形考三--------------------------------

                               // 形考四--------------------------------
                               dragPictureMap.put("慢性肾盂肾炎", "http://xinjiang.ouchn.cn/pluginfile.php/465002/qtype_ddmatch/subanswer/4960119/26/870/%E6%85%A2%E6%80%A7%E8%82%BE%E7%9B%82%E8%82%BE%E7%82%8E.jpg");
                               dragPictureMap.put("慢性纤维空洞", "http://xinjiang.ouchn.cn/pluginfile.php/465002/qtype_ddmatch/subanswer/4960119/26/871/%E6%85%A2%E6%80%A7%E7%BA%A4%E7%BB%B4%E7%A9%BA%E6%B4%9E.jpg");
                               dragPictureMap.put("葡萄胎", "http://xinjiang.ouchn.cn/pluginfile.php/465002/qtype_ddmatch/subanswer/4960119/26/872/%E8%91%A1%E8%90%84%E8%83%8E.jpg");
                               // 形考四--------------------------------

                               System.out.println("答案不存在");
                               System.out.println(title);
                               // title
                               // 遍历图片
                               for (WebElement pic : contentElement.findElements(By.cssSelector("li[class='matchdrag']"))) {
                                   WebElement imgElement = pic.findElement(By.tagName("img"));
                                   String imgUrl = imgElement.getAttribute("src");
                                   //  System.err.println("imgUrlimgUrlimgUrl:" + imgUrl);

                                   for (WebElement tr : contentElement.findElements(By.cssSelector("tr[class='r0'],tr[class='r1']"))) {
                                       WebElement p = tr.findElement(By.tagName("p"));
                                       String aTitle = Util.getTitle(p);
                                       //  System.err.println("text:" + aTitle);
                                       String picUrl = dragPictureMap.get(aTitle.trim());
                                       //    System.err.println("picUrl:" + picUrl);
                                       // 重新作答，题目路径会变，截取后面的。

                                       //if (imgUrl.equals(picUrl)) {
                                       if(picUrl ==null){
                                           continue;
                                       }
//                                    int imgLength = imgUrl.length();
//                                    int picLength = picUrl.length();
                                       if (imgUrl.substring(imgUrl.lastIndexOf("/")).equals(picUrl.substring(imgUrl.lastIndexOf("/")))) {
                                           //  new Actions(driver).dragAndDrop(imgElement, p).perform();
                                           //        new Actions(driver).dragAndDrop(imgElement, tr).perform();
                                           // new Actions(driver).dragAndDrop(imgElement, tr.findElement(By.cssSelector("li[class='placeholder']"))).perform();
                                           new Actions(driver).dragAndDrop(imgElement, tr.findElement(By.cssSelector("td[class='control visibleifjs']"))).perform();
                                           Thread.sleep(2000);
                                       }

                                   }

//                             if(("http://xinjiang.ouchn.cn/pluginfile.php/106141/qtype_ddmatch/subanswer/" +
//                                     "2571061/26/261/%E8%91%A1%E8%90%84%E8%83%8E.jpg").equals(imgUrl)){
//                                 new Actions(driver).dragAndDrop(pic,contentElement.findElement(By.cssSelector("tr[class='r0']")));
//                             }
                                   //    new Actions(driver).dragAndDrop(imgElement,contentElement.findElement(By.cssSelector("tr[class='r0']")));
//                                if(("http://xinjiang.ouchn.cn/pluginfile.php/106141/qtype_ddmatch/subanswer/" +
//                                        "2571061/26/260/%E6%85%A2%E6%80%A7%E7%BA%A4%E7%BB%B4%E7%A9%BA%E6%B4%9E.jpg").equals(imgUrl)){
//                                    new Actions(driver).dragAndDrop(imgElement,
//                                            contentElement.findElement(By.cssSelector("li[class='placeholder']"))).perform();
//                                    new Actions(driver).dragAndDrop(imgElement,
//                                            contentElement.findElement(By.cssSelector("li[class='placeholder']"))).perform();
//                                    for(WebElement p:contentElement.findElements(By.tagName("p"))){
//                                        if(p.getText().equals("Drag answer here")){
//                                            new Actions(driver).dragAndDrop(imgElement, p).perform();
//                                            return;
//                                        }
//                                    }
//                                }
                               }


                               continue;
                           }

                           AnswerObject answerObject = answers.get(questionCode);

                           WebElement answerElement = Util.findByClassName(contentElement, "answer");
                           if (null != answerElement) {
                               // 开始答题
                               Util.doExercise(driver, answerElement, answerObject.getQuestionType(), answerObject.getAnswers());
                           } else {
                               // 如果为空就是填空题 是没有答案对比的
                               Util.doExercise(driver, singleSubject, answerObject.getQuestionType(), answerObject.getAnswers());
                           }
                           //  FIXME 此时答案是没有保存的，要点击结束试答题
                       }
                   } catch (Exception e) {
                       e.printStackTrace();
                   } finally {
                       Thread.sleep(2000);
                       // FIX ME 获取当前页面的下一页信息 设置为while还是有下一页就继续循环
                       WebElement nextPage = Util.findNextPage(driver);
                       if (nextPage != null) {
                           nextPage.click();
                       } else {
                           hashNextPage = false;
                           // FIXME  此时答案是没有保存的，要点击结束试答题 当没有下一页的时候，可以选择提交
                       }
                   }
               }


               Thread.sleep(2000);

               //回到试题首页 (保存最后一题答案)
           /* WebElement element2 = driver.findElement(By.id("quiznavbutton1"));
            element2.click();*/

               WebElement submitbtns = driver.findElement(By.className("submitbtns"));
               WebElement next = submitbtns.findElement(By.cssSelector("input[name='next']"));
               next.click();
               Thread.sleep(2000);

               if (!commit) {
                   log.info("答案不提交");
                   TimeUnit.SECONDS.sleep(2);
                   continue;
               }

               //提交答案
               List<WebElement> saveButtons = driver.findElements(By.cssSelector("button[type='submit']"));
               //System.out.println("提交");
               //System.out.println(saveButtons.size());
               if (!CollectionUtils.isEmpty(saveButtons)) {
                   for (WebElement webElement : saveButtons) {
                       String text = webElement.getText();
                       if (text.contains("提交")) {
                           webElement.click();
                       }
                   }
               }

               TimeUnit.SECONDS.sleep(3);
               //全部提交
               //提交答案

               List<WebElement> confirmation = driver.findElements(By.className("confirmation-dialogue"));
               //System.out.println("确认弹框");
               //System.out.println(confirmation.size());
               //System.out.println(confirmation.toString());
               if (!CollectionUtils.isEmpty(confirmation)) {
                   for (WebElement webElement : confirmation) {
                       List<WebElement> submitElement = webElement.findElements(By.tagName("input"));
//                    System.out.println("再次确认按钮");
//                    System.out.println(submitElement.size());
                       if (!CollectionUtils.isEmpty(submitElement)) {
                           for (WebElement element1 : submitElement) {
                               String value = element1.getAttribute("value");
//                            System.out.println("不是空的");
//                            System.out.println(value);
//                            System.out.println("按钮长这样");
//                            System.out.println(element1.toString());
                               if (value.contains("提交")) {
                                   //点击确认后页面会刷新,此时为了防止丢到元素抛异常，这里直接获取第一个，不再循环
                                   element1.click();
                                   break;
                               }

                           }
                       }
                   }
               }


               List<WebElement> submitButtons = driver.findElements(By.tagName("input"));
               //System.out.println("空的吗");
               //System.out.println(submitButtons.toString());
               if (!CollectionUtils.isEmpty(submitButtons)) {
                   for (WebElement webElement : submitButtons) {
                       String text = webElement.getText();
                       //System.out.println("不是空的");
                       //System.out.println(text);
                       if (text.contains("提交")) {
                           webElement.click();
                       }
                   }
               }

               TimeUnit.SECONDS.sleep(2);
           }catch (Exception e){

           }
        }

        Thread.sleep(5000);
        driver.close();
        driver.quit();
    }


}
